import axios from 'axios'
// import router from '@/router'
// import storage from '@/utils/storage'

const TOKEN_ERROR = "token 认证失败"  // 50001
const NETWORK_ERROR = "网络错误，请检查网络" // 其他

const http = axios.create({
    baseURL: '/api',
    timeout: 8000,
})

http.interceptors.request.use((req) => {
    // const headers= req.headers;
    // const { token = '' } = storage.getItem('userInfo') || {}
    // if (!headers.Authorization) headers.Authorization = 'Bearer ' + token
    console.log('@@@@@@@@444441',req)
    return req
}, err => Promise.reject(err))

http.interceptors.response.use((res) => {
    // const { code, data, msg, status } = res.data

    // // 状态处理
    // if (code === 200) {
    //     return res.data
    // } else if (code === 50001) {
    //     ElMessage.error(TOKEN_ERROR)
    //     setTimeout(() => { router.push('/login') }, 1000)
    //     return Promise.reject(TOKEN_ERROR)
    // } else if (code === 40001) { // 后端返回的错误信息
    //     ElMessage.error(msg)
    //     return Promise.reject(msg)
    // } else {
    //     ElMessage.error(NETWORK_ERROR)
    //     return Promise.reject(NETWORK_ERROR)
    // }
    // console.log('~~~~~~~~~~~~~~~~res',JSON.parse(res.data.data))
    return res.data

}, err => Promise.reject(err))

const request = (options) => {
    // 默认是get请求
    options.method = options.method || 'get'
    // 转成小写比较
    if (["get", "delete"].includes(options.method.toLowerCase())) {
        options.params = options.data
    }
    return http(options);
}

// 给请求添加get、post形式的函数，自动转成简单的处理
["get", "post", "put", "delete", "patch"].forEach((item) => {
    request[item] = (url, data, options) => {
    //   return new Promise((resolve,reject)=>{
    //     let res = {
    //       code:200,
    //       data:JSON.stringify([
    //       {name:'aaa',status:'正常'},
    //       {name:'bbb',status:'正常'},
    //       {name:'ccc',status:'正常'}])}
    //      resolve(res)
    //   })
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request
